package framework.webclient;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openems.ParameterEntities;
import org.openems.ParameterEntity;
import org.openems.entity.Entity;
import org.openems.entity.Key;
import org.openems.entity.ParameterConverter;

import com.google.inject.Inject;


public class EntitySocket implements HttpEntitySocket {

	private RestSocket socket;
//	private RestProperty restProperty;
	private SystemProperty systemProperty;
	private String path;
	
	@Inject
	public EntitySocket(RestSocket socket, String path, SystemProperty systemProp) {
		this.socket = socket;
		this.path = path;
		this.systemProperty = systemProp;
	}
	
	@Override
	public String upload(List<Entity> entities) {
		ParameterEntities parameterEntities = new ParameterEntities();
		parameterEntities.productName = this.systemProperty.getProductName();
		parameterEntities.serialNumber = this.systemProperty.getSerialNumber();
		
		for (Entity entity : entities) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try {
				ObjectOutputStream oos = new ObjectOutputStream(bos);
				oos.writeObject(entity);
				oos.flush();
				bos.flush();
				byte[] body = bos.toByteArray();
				bos.close();		
				ParameterEntity param = new ParameterEntity(entity.getKey().toString(), body);
				parameterEntities.entities.add(param);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		socket.post(this.path, parameterEntities, String.class);
		return null;
	}

	@Override
	public Entity download(Key key) {
		Map<String, String> parameter = new HashMap<String, String>();
		parameter.put("key", key.toString());
		ParameterEntity p = socket.get(path, ParameterEntity.class, parameter);
		if (p.body != null) {
			return new ParameterConverter().get(p.body);
		}
		return null;
	}

	public void delete(Key key) {
		Map<String, String> parameter = new HashMap<String, String>();
		parameter.put("key", key.toString());
		socket.delete(path, String.class, parameter);
	}
}
